package peer.rudp;

import java.util.HashMap;
import java.util.Iterator;

public class ALManage implements Runnable{
	Thread mainThread;
	HashMap<DS2Ident, ALTask> taskTable;
	public ALManage(){
		taskTable=new HashMap<DS2Ident, ALTask>();
		mainThread=new Thread(this);
		mainThread.start();
	}
	
	synchronized void addAck(ConnectionUDP conn,int sequence){
		if(!taskTable.containsKey(conn.di)){
			DS2Ident di=new DS2Ident(conn.di.dstIp,conn.di.dstPort);
			ALTask at=new ALTask(conn);
			taskTable.put(di, at);
		}
		ALTask at=taskTable.get(conn.di);
		at.addAck(sequence);
	}
	
	synchronized void addLastRead(ConnectionUDP conn){
		if(!taskTable.containsKey(conn.di)){
			DS2Ident di=new DS2Ident(conn.di.dstIp,conn.di.dstPort);
			ALTask at=new ALTask(conn);
			taskTable.put(di, at);
		}
	}
	
	
	
	public void run(){
		while(true){
			synchronized (this){
				Iterator it=taskTable.keySet().iterator();
				while(it.hasNext()){
					DS2Ident di=(DS2Ident)it.next();
					ALTask at=taskTable.get(di);
					at.run();
				}
				taskTable=null;
				taskTable=new HashMap<DS2Ident, ALTask>();
			}
			
			try {
				Thread.sleep(peer.Config.alDetectinterval);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
